<?php


namespace App\Models\CacheModel;


use App\Models\CacheModel\lucky\AppUserAdornInfo;
use app\common\lib\ConfigManage;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class GoddessArea extends BaseCache
{
    protected $table = 'wechatadmin.zl_goddess_area';
    public $cacheModel = 'goddess_area.theme';

    /**
     * 获取最新的专区文章
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getNewestArea()
    {
        $time = time();
        return $this->where(['status' => 1, 'publish_time' => ['<', $time]])->order('id', 'DESC')->field('id,title')->find();//获取最新的话题文章信息
    }

    /**
     * 获取女神专区话题信息
     * @param $uid
     * @param $goddessInfo
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getThemeData($uid, $goddessInfo, $page = 1, $limit = 10)
    {
        // 获取女神回复过的所有文章ID
        $goddessReplyThemeIds = $this->getGoddessReplyId(3);
        $topThemeIds = array_slice($goddessReplyThemeIds, 0, 2);
        // 获取24小时最热话题ID
        $hotThemeId = $this->getHourHotThemeId($topThemeIds);
        if ($hotThemeId)
        {
            array_push($topThemeIds, $hotThemeId);
        }
        // 获取所有的话题ID
        $ids = $this->getAllThemeIds();
        // 获取当前分页数据 话题ids
        $thisPageData = $this->getPaginateIds($topThemeIds, $ids, $page, $limit);
        if ($thisPageData['data'])
        {
            // 通过ids 批量获取话题详情
            $themeDatas = $this->batchGetInfo($thisPageData['data'], $goddessReplyThemeIds, ['reply_avatars', 'publish_time', 'title', 'interaction_num', 'goddess_reply_id', 'good_max_comment_id', 'author', 'avatar', 'a_id', 'is_hot', 'author_type']);
            // 重组详情数据
            $thisPageData['data'] = $this->themeDataReset($uid, $thisPageData['data'], $themeDatas, $goddessInfo);

        }
        return $thisPageData;
    }

    public function themeDataReset($uid, $themeIds, $themeDatas, $goddessInfo)
    {
        $goods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 1) : [];
        $data = [];
        $configModle = new ConfigManage();
        foreach ($themeIds as $id)
        {
            if (!isset($themeDatas[$id]))
            {   // 数据不存在则跳过
                continue;
            }
            $replyAvatars = (isset($themeDatas[$id]['reply_avatars']) && $themeDatas[$id]['reply_avatars']) ? explode(',', $themeDatas[$id]['reply_avatars']) : [];

            $content = str_replace('“', '', ($themeDatas[$id]['title'] ?? ''));
            $content = str_replace('”', '', $content);

            $userType = $configModle->innerUser((int)($themeDatas[$id]['a_id'] ?? 0));
            if ($userType === 0)
            {
                $userType = (int)($themeDatas[$id]['author_type'] ?? 0);
            }
            $d = [
                'id' => (int)$id,
                'avatar' => $themeDatas[$id]['avatar'],
                'nickname' => $themeDatas[$id]['author'],
                'time' => $themeDatas[$id]['publish_time'] ? Util::timeToStr($themeDatas[$id]['publish_time']) : '',
                'content' => $content,
                'reply_avatars' => $replyAvatars,
                'is_hot' => (int)$themeDatas[$id]['is_hot'],
                'interaction_num' => (int)($themeDatas[$id]['interaction_num'] ?? 0),
                'reply_hot' => null,
                'user_type' => $configModle->innerUser((int)($themeDatas[$id]['a_id'] ?? 0)),
            ];
            // 获取用户当前装扮信息
            $adorn = (new AppUserAdornInfo())->getUserAdornInfo(0, $userType);
            $d['avatar_adorn'] = $adorn['adorn_info']['reality_img'];
            $d['badge'] = array_column($adorn['badge_info'], 'reality_img');

            if ($themeDatas[$id]['goddess_reply_id'])
            {   // 女神回复
                $replyInfo = (new ArticleCommentReply())->getInfoById($themeDatas[$id]['goddess_reply_id'], ['content_type', 'content', 'comment_id', 'good_num', 'duration']);
                $commentInfo = current((new ArticleComment())->batchGetInfo([$replyInfo['comment_id']], ['uid']));
                $userInfo = current((new \App\Models\Api\User())->batchGetUserInfo([$commentInfo['uid']], ['nickname']));
                $d['reply_hot'] = [
                    'comment_id' => $replyInfo['comment_id'],
                    'nickname1' => $goddessInfo['nickname'] ?? '匿名用户',
                    'nickname2' => $userInfo['nickname'] ?? '匿名用户',
                    'content_type' => (int)$replyInfo['content_type'],
                    'content' => $replyInfo['content'],
                    'duration' => (int)$replyInfo['duration'],
                    'is_goddess' => 1,
                    'is_good' => null,
                    'good_num' => null
                ];
            } elseif ($themeDatas[$id]['good_max_comment_id'])
            {   // 热门回复
                $commentInfo = current((new ArticleComment())->batchGetInfo([$themeDatas[$id]['good_max_comment_id']], ['id', 'uid', 'goods', 'content']));
                $userInfo = current((new \App\Models\Api\User())->batchGetUserInfo([$commentInfo['uid']], ['nickname']));
                $d['reply_hot'] = [
                    'comment_id' => $commentInfo['id'],
                    'nickname1' => $userInfo['nickname'] ?? '匿名用户',
                    'nickname2' => null,
                    'content_type' => 1,
                    'content' => $commentInfo['content'],
                    'duration' => 0,
                    'is_goddess' => 0,
                    'is_good' => in_array($commentInfo['id'], $goods) ? 1 : 0,
                    'good_num' => $commentInfo['goods'] < 0 ? 0 : $commentInfo['goods']
                ];
            }

            $data[] = $d;
        }

        return $data;
    }

    /**
     * 获取女神最近回复的两个话题ID
     * @param int $type
     * @return array
     * @throws \Exception
     */
    public function getGoddessReplyId($type = 3): array
    {
        if (!in_array($type, [1, 2, 3], true))
        {
            return [];
        }

        $data = CacheManage::getInstance()->setCacheConfig('goddess_area.goddess_reply_article', $type)
            ->setSort('desc')->ZsGetIocData('list', function () use ($type)
            {
                try
                {
                    $tableNameType = [
                        1 => 'wechatadmin.system_article',
                        2 => 'wechatadmin.zl_goddess_state',
                        3 => 'wechatadmin.zl_goddess_area',
                    ];

                    return $this->table('wechatadmin.system_comment_reply')->alias('r')
                        ->join("{$tableNameType[$type]} a", 'a.id=r.aid')
                        ->where('a.status', 1)
                        ->where(['r.type' => 3, 'r.is_goddess' => 1])->group('aid')->column('max(r.create_time)', 'r.aid');
                }
                catch (\Exception $e)
                {
                    return [];
                }
            });

        return $data;
    }

    /**
     * 获取24小时回复最热的话题ID（一个）
     * @param array $topThemeIds
     * @return int|null
     * @throws \Exception
     */
    public function getHourHotThemeId(array $topThemeIds = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig('goddess_area.theme_reply_time_num')
            ->setSort('desc')->ZsGetIocData('list', function ()
            {
                try
                {
                    $time = time() - 86400;
                    $replyNum = $this->table('wechatadmin.system_comment_reply')->where(['type' => 3, 'status' => 0])->where('create_time', '>', $time)->group('aid')->column('count(*)', 'aid');
                    $commentNum = $this->table('wechatadmin.system_article_comment')->where(['type' => 3, 'status' => 0])->where('create_time', '>', $time)->group('aid')->column('count(*)', 'aid');

                    foreach ($replyNum as $aid => $num)
                    {
                        if (isset($commentNum[$aid]))
                        {
                            $replyNum[$aid] += $commentNum[$aid];
                            unset($commentNum[$aid]);
                        }
                    }
                    $resNum = $replyNum + $commentNum;

                    arsort($replyNum);

                    return $resNum;

                }
                catch (\Exception $e)
                {
                    return [];
                }
            });

        $resIds = array_diff($data, $topThemeIds);

        $hotId = array_shift($resIds);

        return $hotId;
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function getAllThemeIds()
    {
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setSort('desc')->ZsGetIocData('list', function ()
        {
            $data = $this->where('status', 1)->where('publish_time', '<', time())->order('sort desc,publish_time desc')->column('publish_time,sort', 'id');
            $ids = [];

            foreach ($data as $id => $datum)
            {
                $ids[$id] = (float)($datum['sort'] . '.' . $datum['publish_time']);
            }

            return $ids;
        }, true);

        return $ids;
    }

    /**
     * 获取首页话题信息 v2.6.0
     */
    public function getHomeThemeData()
    {
        // 获取女神回复过的所有文章ID
        $goddessReplyThemeIds = $this->getGoddessReplyId(3);
        // 获取所有的话题ID
        $ids = $this->getHomeThemeIds();
        $ids = array_keys($ids);
        $data = [];
        $resData = [];
        if ($ids)
        {
            $themeDatas = $this->batchGetInfo($ids, $goddessReplyThemeIds, ['title', 'interaction_num', 'is_hot', 'read_num', 'comment_num']);

            foreach ($ids as $id)
            {
                if (!isset($themeDatas[$id]))
                {   // 数据不存在则跳过
                    continue;
                }
                $hot_num = (int)(($themeDatas[$id]['read_num'] + $themeDatas[$id]['comment_num']) * 2.6);

                $content = str_replace(['“', '”'], '', ($themeDatas[$id]['title'] ?? ''));

                $data[] = [
                    'id' => $id,
                    'content' => $content,
                    'is_hot' => $themeDatas[$id]['is_hot'] ? 1 : 0,
                    'desc' => $hot_num,
                ];
            }
            $s = array_column($data, 'desc');
            array_multisort($s, SORT_DESC, $data); // 根据热度排序

            foreach ($data as $datum)
            {

                if ($datum['desc'] > 10000)
                {
                    $datum['desc'] = sprintf('%.1f', $datum['desc'] / 10000) . 'W';
                }

                $datum['desc'] = $datum['desc'] . '热度';
                $resData[] = $datum;
            }
        }

        return $resData;
    }

    /**
     * 获取首页话题ID v2.6.0
     * @return array
     * @throws \Exception
     */
    public function getHomeThemeIds()
    {
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, 'home')->setSort('desc')->ZsGetIocData('list', function ()
        {
            $data = $this->where('status', 1)->where('is_home', 1)->where('publish_time', '<', time())->order('sort desc,publish_time desc')->column('publish_time,sort', 'id');
            $ids = [];

            foreach ($data as $id => $datum)
            {
                $ids[$id] = (float)($datum['sort'] . '.' . $datum['publish_time']);
            }

            return $ids;
        }, true);

        return $ids;
    }

    /**
     * 获取当前页数的话题ID和分页数据结构
     * @param array $topThemeIds 置顶的话题IDS
     * @param array $ids 所有的话题IDs
     * @param int $page 当前页数
     * @param int $limit 每页显示数量
     * @return array
     */
    public function getPaginateIds(array $topThemeIds, array $ids, int $page, int $limit)
    {
        // $topNum = count($topThemeIds); // 置顶主题数量
        // // 获取有效的话题ID  去除已经置顶了的ID
        // $idData = array_diff($ids, $topThemeIds);
        // $total = count($ids); // 总话题数
        // $lastPage = (int)ceil($total / $limit); // 总页数
        //
        // $themeIds = [];
        // if ($page <= 1)
        // { // 第一页
        //     $len = $limit - $topNum;
        //     $themeIds = array_merge($topThemeIds, array_slice($idData, 0, $len));
        // } elseif ($page > 1 && $page <= $lastPage)
        // { // 第二页++++
        //     $star = ($page - 1) * $limit - $topNum;
        //     $themeIds = array_slice($idData, $star, $limit);
        // }

        foreach ($topThemeIds as $index => $idItem)
        {
            if (isset($ids[$idItem]) && $ids[$idItem] < 100000)
            {
                $ids[$idItem] = 70000 - $index;
            }
        }

        arsort($ids);

        $ids = array_keys($ids);

        $total = count($ids); // 总话题数
        $lastPage = (int)ceil($total / $limit); // 总页数

        $star = ($page - 1) * $limit;
        $themeIds = array_slice($ids, $star, $limit);

        return [
            'total' => $total,// 记录总数
            'per_page' => $limit,// 每页多少条
            'current_page' => $page,// 当前页数
            'last_page' => $lastPage,// 总页数
            'data' => $themeIds,
        ];
    }

    /**
     * 通过ID批量获取话题详情
     * @param $ids
     * @param $goddessReplyThemeIds // 女神回复的话题IDs
     * @param array $filed
     * @return array
     * @throws \Exception
     */
    protected function batchGetInfo($ids, $goddessReplyThemeIds, array $filed = [])
    {
        $themeDatas = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->batchGetCache($ids, function ($ids) use ($goddessReplyThemeIds)
            {
                try
                {
                    $themeData = $this->alias('a')
                        ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id', 'LEFT')
                        ->where(['a.id' => ['in', $ids]])
                        ->column('a.title,a.good_num,a.collect_num,a.comment_num,a.reply_avatars,a.interaction_num,a.publish_time,a.read_num,a.read_base,u.name author,u.type author_type,u.thumb avatar,u.uid a_id,a.is_hot,a.is_top,a.extend', 'a.id');

                    foreach ($themeData as $id => $themeItem)
                    {
                        if (in_array($id, $goddessReplyThemeIds))
                        { // 女神回复过该主题
                            $replyId = $this->table('wechatadmin.system_comment_reply')
                                ->where(['type' => 3, 'aid' => $id, 'is_goddess' => 1, 'status' => 0])
                                ->order('content_type desc,create_time desc')
                                ->value('id');
                            $themeData[$id]['goddess_reply_id'] = $replyId ?? 0; // 女神回复的回复ID
                            $themeData[$id]['reply_good_max_num'] = 0; // 回复点赞最多的点赞数 一级回复
                            $themeData[$id]['good_max_comment_id'] = 0; // 回复点赞最多的回复ID 一级回复
                        } else
                        {
                            $commentData = $this->table('wechatadmin.system_article_comment')
                                ->where(['type' => 3, 'aid' => $id])->order('goods desc')
                                ->field('id,goods')->find();
                            if ($commentData && $commentData->goods > 100)
                            {
                                $themeData[$id]['goddess_reply_id'] = 0; // 女神回复的回复ID
                                $themeData[$id]['reply_good_max_num'] = $commentData->goods; // 回复点赞最多的点赞数 一级回复
                                $themeData[$id]['good_max_comment_id'] = $commentData->id; // 回复点赞最多的回复ID 一级回复
                            } else
                            {
                                $themeData[$id]['goddess_reply_id'] = 0; // 女神回复的回复ID
                                $themeData[$id]['reply_good_max_num'] = 0; // 回复点赞最多的点赞数 一级回复
                                $themeData[$id]['good_max_comment_id'] = 0; // 回复点赞最多的回复ID 一级回复
                            }
                        }
                    }
                }
                catch (\Exception $e)
                {
                    $themeData = [];
                }

                return $themeData;
            }, $filed, 'list_details');

        return $themeDatas;
    }

    /**
     * 获取话题详情信息
     * @param int|array|string $ids 15 | [15,13,26] | 15,13,26
     * @param array $filed
     * @return array
     * @throws \Exception
     */
    public function batchGetThemeInfo($ids, array $filed = [])
    {
        // 获取女神回复过的所有文章ID
        $goddessReplyThemeIds = $this->getGoddessReplyId(3);

        return $this->batchGetInfo($ids, $goddessReplyThemeIds, $filed);
    }

    /**
     * 互动头像
     * @param int $aid
     * @param string $avatar
     * @param array $themeInfo
     * @throws \Exception
     */
    public function interactionAvatars(int $aid, string $avatar = '', array $themeInfo): void
    {
        $avatarData = $themeInfo['reply_avatars'] ? explode(',', $themeInfo['reply_avatars']) : [];
        if ($avatar && count($avatarData) < 3 && !in_array($avatar, $avatarData, true))
        {   // 头像不为空  互动头像数量不足3个 并且 用户头像之前并不存在
            $avatarData[] = $avatar;
            $avatarDataStr = ['reply_avatars' => implode(',', $avatarData)];
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $aid)->setCache($avatarDataStr);
            if (count($avatarData) >= 3)
            {
                $this->where('id', $aid)->update($avatarDataStr);
            }
        }
    }
}
